import 'package:flutter/material.dart';
import 'package:x3_base_core/x3_base_core.dart';
import 'package:x3_component_core/x3_component_core.dart';

class ListViewSingleChoiceComponent extends StatefulWidget {
  final List<BaseKeyValueModel> items;
  final BaseKeyValueModel selectedItem;
  final double itemExtent;
  final Widget Function(BuildContext context, int index, BaseKeyValueModel item) itemBuilder;

  /// 在item显示的样式为[key]value
  final bool itemShowKey;

  /// 选中事件
  final Function(BaseKeyValueModel selected) selectedEvent;

  const ListViewSingleChoiceComponent({Key key, @required this.items, this.selectedItem, this.itemBuilder, @required this.selectedEvent, this.itemExtent = 49.0, this.itemShowKey = false}) : super(key: key);

  @override
  State<ListViewSingleChoiceComponent> createState() => _ListViewSingleChoiceComponentState();
}

class _ListViewSingleChoiceComponentState extends State<ListViewSingleChoiceComponent> {
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      shrinkWrap: true,
      itemExtent: widget.itemExtent,
      itemCount: widget.items.length,
      itemBuilder: _buildDefaultItem,
    );
  }

  /// 创建每行 item
  Widget _buildDefaultItem(BuildContext context, int index) {
    BaseKeyValueModel item = widget.items[index];
    bool isSelected = widget.selectedItem != null && widget.selectedItem.key == item.key;
    return InkWell(
      child: widget.itemBuilder != null ? widget.itemBuilder(context, index, widget.items[index]) : _buildItemContent(item, isSelected),
      onTap: () {
        Navigator.of(context, rootNavigator: true).pop();
        if (!isSelected) {
          setState(() {
            widget.selectedEvent(item);
          });
        }
      },
    );
  }

  /// 创建item
  Widget _buildItemContent(BaseKeyValueModel item, bool isSelected) {
    return Container(
      height: 49,
      child: Column(
        children: [
          _buildItem(item, isSelected),
          BaseComponentUtils.buildHorizontalDivider(),
        ],
      ),
    );
  }

  /// 默认模板
  Widget _buildItem(BaseKeyValueModel item, bool isSelected) {
    return Container(
      color: isSelected == true ? Color(0xFFF3F3F3) : Colors.transparent,
      alignment: Alignment.center,
      height: 48,
      child: Text(widget.itemShowKey ? '[${item.key}]${item.value ?? ''}' : item.value ?? '', style: BaseStyles.bodyMedium(context)),
    );
  }
}
